package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.media.dtos.WmUserDto;
import com.heima.model.media.pojos.WmUser;
import com.heima.utils.common.AppJwtUtil;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;

@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper,WmUser> implements WmUserService {
    @Override
    public ResponseResult login(WmUserDto dto) {
        //检查参数
        if(dto==null){
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //检查是否输入用户名及密码
        if(StringUtils.isBlank(dto.getName())||StringUtils.isBlank(dto.getPassword())){
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //根据用户名查询用户数据
        WmUser one = getOne(Wrappers.<WmUser>lambdaQuery().eq(WmUser::getName, dto.getName()));
        if(one==null){
            CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //比较密码
        String realPassword = one.getPassword();
        String md5Password = DigestUtils.md5DigestAsHex((dto.getPassword() + one.getSalt()).getBytes());
        if(!realPassword.equals(md5Password)){
            CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //封装信息返回
        String token = AppJwtUtil.getToken(Long.valueOf(one.getId()));
        HashMap<String, Object> map = new HashMap<>();
        one.setPassword("");
        one.setSalt("");
        map.put("user",one);
        map.put("token",token);
        return ResponseResult.okResult(map);
    }
}
